<?php

/**
 * @copyright: ©2024 永州微聚 商网络科技有限公司
 * @link: https://www.weijuYunke.com
 */
namespace app\mobile\controller;

use app\admin\model\HelpTutoria;
use app\BaseController;
use think\App;
use think\Exception;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureSystem;
use app\admin\model\FigurePayLog;
use app\admin\model\FigureNavigation;
use app\admin\model\FigureBanner;
use app\admin\model\FigureService;
use app\admin\model\FigureCard;
use app\admin\model\FigureCardGoods;
use app\admin\model\FigureCardLog;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigureUser;
use app\common\service\ApiService;
use think\file\UploadedFile;
use FFMpeg\FFMpeg;
use app\common\service\Sms;
use app\admin\model\FigureIndexSet;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true'); // 是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); // 允许的请求类型
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// 允许的请求头字段

/**
 * 首页
 *
 * @author Administrator
 *        
 */
class Index extends BaseController
{

    /**
     * http://aigc.weijuyunke.cn/mobile/index/test
     */
    public function test()
    {
        try {
            
            $card = 'THE5d7iIXyAE';
            
            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (! empty($password)) {
                $redis->auth($password);
            }
            
            $redis->del("card-" . $card);
            
            print_r(array(
                'redis' => $redis->get("card-" . $card)
            ));
            exit();
            
            // 关闭连接
            $redis->close();
            
            $name = time() . rand(999, 9999);
            
            $path = root_path() . 'public/uploads/video';
            
            if (! is_dir($path)) {
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }
            
            $path .= '/video-' . $name . '.mp4';
            
            // 使用cURL下载视频
            $ch = curl_init("https://f2gy8xbzniwgakhtsnow.deepln.com/video/cd9f756d64b64213b1e30462735766b6.mp4");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoData = curl_exec($ch);
            curl_close($ch);
            
            // 将视频数据保存到本地文件
            $videoFile = fopen($path, 'wb');
            fwrite($videoFile, $videoData);
            
            require_once root_path() . "vendor/getID3-master/getid3/getid3.php";
            
            $getID3 = new \getID3();
            $fileInfo = $getID3->analyze($path);
            
            fclose($videoFile);
            unlink($path);
            
            print_r(array(
                'fileInfo' => $fileInfo
            ));
            exit();
            
            if (isset($fileInfo['video']['thumbnail'][0])) {
                $thumbnailData = $fileInfo['video']['thumbnail'][0]['data'];
                file_put_contents($outputPath, $thumbnailData);
            }
            
            $type = input('type');
            $url = input('url');
            $duration = getDuration($type, $url);
            print_r(array(
                'duration' => $duration
            ));
            exit();
            
            $ticket_url = "https://open.douyin.com/js/getticket/";
            
            $ticket_obj = headerGet($ticket_url, array(
                'access-token: ' . 'clt.82db7efecb542c8b94e4b24d3bd02689zpTLRiaXXP3cvccnfWE9pQC3bKU3_lq'
            ));
            $ticket_data = json_decode($ticket_obj, true);
            
            if (isset($ticket_data['data']['error_code']) && ! empty($ticket_data['data']['error_code'])) {
                
                return result(- 1, 'ticket--->' . $ticket_data['data']['description']);
                exit();
            }
            
            print_r(array(
                'ticket_data' => $ticket_data
            ));
            exit();
            
            $apiService = new ApiService();
            $result = $apiService->test();
            
            print_r(array(
                'result' => $result
            ));
            exit();
            
            $this->updateCard('CA2024072056529749', 0.04);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 大屏首页
     * http://aigc.weijuyunke.cn/mobile/index/screen_index
     */
    public function screen_index()
    {
        return view("screen_index");
    }

    /**
     * DY首页
     * http://aigc.weijuyunke.cn/mobile/index/dy_index
     */
    public function dy_index()
    {
        $video_id = input('video_id');
        // Db::table('wjyk_figure_video')->where('id', $video_id)->setInc('scan_code', 1);
        return view("dy_index");
    }

    /**
     * KS首页
     * http://aigc.weijuyunke.cn/mobile/index/ks_index
     */
    public function ks_index()
    {
        $video_id = input('video_id');
        // Db::table('wjyk_figure_video')->where('id', $video_id)->setInc('scan_code', 1);
        return view("ks_index");
    }
    public function kshtml(){
        return view("ks_index");
    }

    /**
     * 阿里云配置
     * http://aigc.weijuyunke.cn/mobile/index/aliyunConfig
     */
    public function aliyunConfig()
    {
        return result(0, 'success', [
            'alioss_access_key_id' => sysconfig('upload', 'alioss_access_key_id'),
            'alioss_access_key_secret' => sysconfig('upload', 'alioss_access_key_secret'),
            'alioss_endpoint' => sysconfig('upload', 'alioss_endpoint'),
            'alioss_bucket' => sysconfig('upload', 'alioss_bucket'),
            'alioss_domain' => sysconfig('upload', 'alioss_domain')
        ]);
    }

    /**
     * 退款
     * http://aigc.weijuyunke.cn/mobile/index/refund
     *
     * @param
     *            log_no 订单编号
     * @param
     *            price 退款金额
     */
    public function refund()
    {
        try {
            $log_no = input('log_no');
            $price = input('price');


            
            $res = json_decode(order_refund($log_no, $price, $price), true);
            
            if ($res['code'] == 1) {
                return result(0, '退款成功');
            } else {
                return result(- 1, $res);
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 首页设置
     * http://aigc.weijuyunke.cn/mobile/index/indexSet
     */
    public function indexSet()
    {
        $set = FigureIndexSet::where("id", 1)->find();
        
        if (empty($set)) {
            $set = [];
        }
        
        return result(0, 'success', $set);
    }

    /**
     * 获取图片宽高
     * http://aigc.weijuyunke.cn/mobile/index/getImageSize
     *
     * @param
     *            url
     */
    public function getImageSize()
    {
        $url = input('url');
        
        $info = getimagesize($url);
        
        return result(0, 'success', $info);
    }

    /**
     * 获取时长
     * http://aigc.weijuyunke.cn/mobile/index/getDuration
     *
     * @param
     *            url
     * @param
     *            type 1-音频 2-视频
     */
    public function getDuration()
    {
        try {
            $type = input('type');
            $url = input('url');
            $duration = getDuration($type, $url);
            
            return result(0, 'success', $duration);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 支付设置
     * http://aigc.weijuyunke.cn/mobile/index/payconfig
     */
    public function payconfig()
    {
        return result(0, 'success', [
            'pay_open' => sysconfig('pay', 'pay_open')
        ]);
    }
    /**
     * 模板设置
     * http://aigc.weijuyunke.cn/mobile/index/template
     */
    public function template()
    {
        $set = sysconfig('template');
        
        if (empty($set)) {
            $set = [];
        }
        
        return result(0, 'success', $set);
    }

    /**
     * 扣点设置
     * http://aigc.weijuyunke.cn/mobile/index/tallySet
     */
    public function tallySet()
    {
        try {
            $set = sysconfig('tally');
            
            if (empty($set)) {
                $set = [];
            }
            
            return result(0, 'success', $set);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 客服设置
     * http://aigc.weijuyunke.cn/mobile/index/kfSet
     */
    public function kfSet()
    {
        try {
            $siteSet = sysconfig('site');
            
            if (empty($siteSet)) {
                $set = [];
            } else {
                $set = [
                    'kf_date' => $siteSet['kf_date'],
                    'kf_img' => $siteSet['kf_img'],
                    'kf_mailbox' => $siteSet['kf_mailbox'],
                    'kf_phone' => $siteSet['kf_phone'],
                    'kf_wxno' => $siteSet['kf_wxno'],
                    'kf_address' => $siteSet['kf_address'],
                    'upload_describe' => $siteSet['upload_describe'],
                    'upload_describe_swich' => $siteSet['upload_describe_swich'],
                    'help_switch' => $siteSet['help_switch'],
                    'clip_swtich' => $siteSet['clip_swtich'],



                ];
            }
            
            return result(0, 'success', $set);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 系统设置
     * http://aigc.weijuyunke.cn/mobile/index/system
     */
    public function system()
    {
        $t = time();
        FigureUser::where('maturity_time', '<', $t)->update([
            'is_member' => 0
        ]);

        $system = FigureSystem::where("id", 1)->find();
        
        if (empty($system)) {
            $system = [];
        }
        $siteSet = sysconfig('site');
        $system['link_require'] = $siteSet['link_require'];
        $system['copywriting_require'] = $siteSet['copywriting_require'];
        $system['kouzhi_swich'] = $siteSet['kouzhi_swich'];
        $set = sysconfig('forward');
        $system['k_xiaochengxu'] = $set['k_xiaochengxu'];
        return result(0, 'success', $system);
    }

    /**
     * 轮播图
     * http://aigc.weijuyunke.cn/mobile/index/banner
     *
     * @param
     *            b_type 1-首页 2-卡密商城3-AI创作
     */
    public function banner()
    {
        $request = $this->request;
        $condition['is_display'] = 1 ;
        
        if (! empty($request->param('b_type'))) {
            $b_type = $request->param('b_type');
            $condition['b_type'] =  $b_type;
        }
        
        $list = FigureBanner::where($condition)->order('sort', 'desc')->select();
        
        if (empty($list)) {
            $list = [];
        }
        
        return result(0, 'success', $list);
    }

    /**
     * 服务图片
     * http://aigc.weijuyunke.cn/mobile/index/service
     */
    public function service()
    {
        $request = $this->request;
        
        $condition = " is_display = 1";
        
        $list = FigureService::where($condition)->order('sort', 'desc')->select();
        
        if (empty($list)) {
            $list = [];
        }
        
        return result(0, 'success', $list);
    }

    /**
     * 导航
     * http://aigc.weijuyunke.cn/mobile/index/navigation
     */
    public function navigation()
    {
        $request = $this->request;
        
        $condition = " is_display = 1";
        
        $list = FigureNavigation::where($condition)->order('sort', 'desc')->select();
        
        if (empty($list)) {
            $list = [];
        }
        
        return result(0, 'success', $list);
    }

    /**
     * 短信设置
     * http://aigc.weijuyunke.cn/mobile/index/noteConfig
     */
    public function noteConfig()
    {
        return result(0, 'success', [
            'note_open' => sysconfig('note', 'note_open')
        ]);
    }

    /**
     * 短信验证
     * https://knead.admin168.net/mobile/index/sendMobile
     *
     * @param
     *            telphone(电话号码)
     */
    public function sendMobile()
    {
        try {
            
            $note = sysconfig('note');
            
            if (empty($note)) {
                return result(- 1, '请在管理平台设置短信有关信息！');
            }
            
            $telphone = input('telphone');
            if (empty($telphone)) {
                return result(- 1, '电话号码错误！');
            }
            
            $number = getRandNumber(0, 9, 6);
            
            if ($note['note_type'] == 1) {
                
                $user = $note['note_user']; // 短信平台帐号
                $pass = $note['note_pass']; // 短信平台密码
                $signature = $note['note_signature']; // 短信平台签名
                
                $url = "https://api.mix2.zthysms.com/v2/sendSmsTp"; // 短信网关
                $tKey = time();
                $password = md5(md5($pass) . $tKey);
                
                $records = array();
                $records[] = array(
                    'mobile' => $telphone,
                    'tpContent' => array(
                        "valid_code" => $number
                    )
                );
                
                $data = array(
                    'username' => $user, // 用户名,
                    'password' => $password, // 密码
                    'tKey' => $tKey,
                    'signature' => "【" . $signature . "】",
                    'tpId' => $note['note_verify_code'],
                    'records' => $records
                );
                
                $ret = httpPost($url, $data);
                
                $json = json_decode($ret, true);
                if ($json['code'] == 200) {
                    return result(0, 'success', $number);
                } else {
                    return result(- 1, $json);
                }
            } elseif ($note['note_type'] == 2) {
                $config = [
                    'accessKeyId' => $note['note_key_id'],
                    'accessKeySecret' => $note['note_key_secret'],
                    'signName' => $note['note_sign_name'],
                    'templateCode' => $note['note_verify_code']
                ];
                
                $sms = new Sms($config);
                $status = $sms->send_verify($telphone, $number);
                
                if ($sms->error == 'OK') {
                    return result(0, 'success', $number);
                } else {
                    return result(- 1, $sms->error);
                }
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 微信支付
     * http://aigc.weijuyunke.cn/mobile/index/pay
     *
     * @param
     *            log_no 订单编号
     * @param
     *            price 金额
     * @param
     *            openid
     * @param
     *            name 商品名称
     */
    public function pay()
    {
        try {
            $request = $this->request;
            $user_id = $this->request->_UID;
            
            $openid = input("openid");
            $price = input('price');
            $payno = empty(input('log_no')) ? getPayNo('PAY') : input('log_no');
            $name = empty(input('name')) ? '支付' : input('name');
            
            if (empty($price)) {
                return result(- 1, "金额为空");
            }
            
            if (empty($openid)) {
                return result(- 1, "openid为空");
            }
            
            $payconfig = sysconfig('pay');
            
            if (empty($payconfig)) {
                return result(- 1, "请检查支付配置");
            }
            
            $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            
            $nonce_str = getNonceStr(32);
            $domain = $request->domain();
            
            $pay_type = $payconfig['pay_type'];
            
            if ($pay_type == 2) { // 子商户支付
                $send_data = array(
                    'appid' => $payconfig['pay_service_appid'],
                    'mch_id' => $payconfig['pay_service_mchid'],
                    'sub_appid' => $payconfig['pay_appid'],
                    'sub_mch_id' => $payconfig['pay_mchid'],
                    'nonce_str' => $nonce_str,
                    'body' => $name,
                    'out_trade_no' => $payno,
                    'total_fee' => $price * 100,
                    'notify_url' => $domain . '/mobile/index/notify',
                    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                    'trade_type' => 'JSAPI',
                    'sub_openid' => $openid
                );
            } else {
                $send_data = array(
                    'appid' => $payconfig['pay_appid'],
                    'mch_id' => $payconfig['pay_mchid'],
                    'nonce_str' => $nonce_str,
                    'body' => $name,
                    'out_trade_no' => $payno,
                    'total_fee' => $price * 100,
                    'notify_url' => $domain . '/mobile/index/notify',
                    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                    'trade_type' => 'JSAPI',
                    'openid' => $openid
                );
            }
            
            $pay_key = $payconfig['pay_api_key'];
            $sign = MakeSign($send_data, $pay_key);
            $send_data['sign'] = $sign;
            $result = FromXml(wtw_request($url, ToXml($send_data)));
            
            if (isset($result['result_code']) && isset($result['return_code']) && $result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                
                if ($pay_type == 2) {
                    $ret = sign_pay($result, $send_data['sub_appid'], $pay_key);
                } else {
                    $ret = sign_pay($result, $send_data['appid'], $pay_key);
                }
                $ret['out_trade_no'] = $send_data['out_trade_no'];
                
                return result(0, 'success', $ret);
            } else {
                return result(- 1, isset($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'], $send_data);
            }
        } catch (\Exception $e) {
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getLine());
        }
    }

    /**
     * 支付回调
     */
    public function notify()
    {
        $request = $this->request;
        $user_id = $this->request->_UID;
        
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); // 转成数组，
        
        Log::write("Index notify--->" . $jsonxml, 'info');
        if ($result) {
            
            $data = array(
                'type' => 1,
                'out_trade_no' => empty($result['out_trade_no']) ? '' : $result['out_trade_no'],
                'total_fee' => empty($result['total_fee']) ? '' : $result['total_fee'] * 0.01,
                'return_code' => empty($result['return_code']) ? '' : $result['return_code'],
                'result_code' => empty($result['result_code']) ? '' : $result['result_code'],
                'attach' => empty($result['attach']) ? '' : $result['attach'],
                'transaction_id' => empty($result['transaction_id']) ? '' : $result['transaction_id'],
                'err_code' => empty($result['err_code']) ? '' : $result['err_code'],
                'err_code_des' => empty($result['err_code_des']) ? '' : $result['err_code_des'],
                'result' => json_encode($result)
            );
            
            $log = FigurePayLog::where("out_trade_no", $data['out_trade_no'])->find();
            
            if (empty($log)) {
                $payLog = new FigurePayLog();
                $payLog->save($data);
            } else {
                FigurePayLog::where("out_trade_no", $data['out_trade_no'])->update($data);
            }
            
            if (strpos($result['out_trade_no'], 'PA') !== false) {
                Partner::update_partner($data['out_trade_no'], $data['total_fee']);
            }
            
            if (strpos($result['out_trade_no'], 'CA') !== false) {
                $this->updateCard($data['out_trade_no'], $data['total_fee']);
            }
            
            if (strpos($result['out_trade_no'], 'ME') !== false) {
                Member::update_member($data['out_trade_no'], $data['total_fee']);
            }
            
            if (strpos($result['out_trade_no'], 'PT') !== false) {
                Member::update_point($data['out_trade_no'], $data['total_fee']);
            }
            if (strpos($result['out_trade_no'], 'FR') !== false) {
                ResourcesOrder::orderCallback($data['out_trade_no'], $data['total_fee']);
            }
        }
    }

    /**
     * 上传网络视频
     * http://aigc.weijuyunke.cn/mobile/index/toLocal
     *
     * @param
     *            url
     */
    public function toLocal()
    {
        try {
            
            set_time_limit(0);
            ini_set("memory_limit", "1024M");
            ini_set('max_execution_time', 1000);
            
            $url = input('url');
            if (empty($url)) {
                return result(- 1, "url为空");
            }
            
            $name = time() . rand(999, 9999);
            
            $path = root_path() . 'public/uploads/video';
            
            if (! is_dir($path)) {
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }
            
            $path .= '/video-' . $name . '.mp4';
            
            // 使用cURL下载视频
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoData = curl_exec($ch);
            curl_close($ch);
            
            // 将视频数据保存到本地文件
            $videoFile = fopen($path, 'wb');
            fwrite($videoFile, $videoData);
            
            $file = new UploadedFile($path, $name . '.mp4');
            
            $upload = sysconfig('upload');
            $extension = "mp4";
            if (empty($upload['upload_type']) || $upload['upload_type'] == 'local') {
                $domain = request()->domain();
                $paths = $domain . "/uploads/video/video-" . $name . '.mp4';
            } elseif ($upload['upload_type'] == 'alioss') {
                
                $accesskey = $upload['alioss_access_key_id'];
                $secretkey = $upload['alioss_access_key_secret'];
                $bucket = $upload['alioss_bucket'];
                $domain = $upload['alioss_domain'];
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $ossClient = new \OSS\OssClient($accesskey, $secretkey, 'oss-accelerate.aliyuncs.com');
                $ossClient->uploadFile($bucket, $key, $path);
                $paths = "https://" . $domain . "/" . $key;
            } elseif ($upload['upload_type'] == 'qnoss') {
                
                $accesskey = $upload['qnoss_access_key'];
                $secretkey = $upload['qnoss_secret_key'];
                $bucket = $upload['qnoss_bucket'];
                $domain = $upload['qnoss_domain'];
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $auth = new \Qiniu\Auth($accesskey, $secretkey);
                // 生成上传 Token
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new \Qiniu\Storage\UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list ($ret, $err) = $uploadMgr->putFile($token, $key, $path);
                if ($err !== null) {
                    return result(- 1, '上传失败');
                } else {
                    $paths = $domain . "/" . $ret['key'];
                }
            } elseif ($upload['upload_type'] == 'txcos') {
                
                $accesskey = $upload['txcos_secret_id'];
                $secretkey = $upload['txcos_secret_key'];
                $bucket = $upload['txcos_bucket'];
                $domain = $upload['txcos_region'];
                
                $file = fopen($path, "rb");
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $cosClient = new \Qcloud\Cos\Client([
                    'region' => $domain,
                    'schema' => "https",
                    'credentials' => [
                        'secretId' => $accesskey,
                        'secretKey' => $secretkey
                    ]
                ]);
                
                $result = $cosClient->putObject([
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file
                ]);
                
                $paths = "https://" . $bucket . ".cos." . $domain . ".myqcloud.com/" . $key;
            }
            
            unlink($path);
            
            fclose($videoFile);
            
            return result(0, 'success', $paths);
        } catch (\Exception $e) {
            Log::write("toLocal 失败" . json_encode($e->getTrace()), 'info');
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * 上传图片
     * http://aigc.weijuyunke.cn/mobile/index/upload
     *
     * @param
     *            file
     */
    public function upload()
    {
        try {
            
            set_time_limit(0);
            ini_set("memory_limit", "1024M");
            ini_set('max_execution_time', 1000);
            
            $file = request()->file('file'); // 获取上传的文件
            
            $upload = sysconfig('upload');
            
            if (empty($upload)) {
                return result(- 1, '请检查上传配置');
            }
            
            $file = $_FILES['file'];
            $filePath = $file['tmp_name'];
            $temp = explode("/", $file['type']); // 获取文件名按“.”进行分割
            
            Log::write("upload -->" . json_encode([
                'file' => $file,
                'path' => pathinfo($file['name'], PATHINFO_EXTENSION)
            ]), 'info');
            
            $extension = end($temp);
            
            if ($file['type'] == 'audio/mpeg') {
                $path = pathinfo($file['name'], PATHINFO_EXTENSION);
                $extension = $path == 'm4a' ? "m4a" : "mp3";
            }
            
            if ($file['type'] == 'audio/mp4') {
                $path = pathinfo($file['name'], PATHINFO_EXTENSION);
                $extension = $path == 'm4a' ? "m4a" : "mp4";
            }
            
            if ($file['type'] == 'audio/x-m4a') {
                $path = pathinfo($file['name'], PATHINFO_EXTENSION);
                $extension = $path == 'm4a' ? "m4a" : "mp4";
            }
            
            if ($file['type'] == 'audio/vnd.wave' || $file['type'] == 'audio/x-wav') {
                $path = pathinfo($file['name'], PATHINFO_EXTENSION);
                $extension = $path == 'wav' ? "wav" : "mp4";
            }
            
            if ($file['type'] == 'audio/wave') {
                $extension = "wave";
            }
            
            if ($upload['upload_type'] == 'local') {
                $saveName = \think\facade\Filesystem::disk('public')->putFile('uploads', $file, 'data');
                $domain = request()->domain();
                $img = $domain . "/" . $saveName;
                return result(0, 'success', $img);
            } elseif ($upload['upload_type'] == 'alioss') {
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $accesskey = $upload['alioss_access_key_id'];
                $secretkey = $upload['alioss_access_key_secret'];
                $bucket = $upload['alioss_bucket'];
                $domain = $upload['alioss_domain'];
                
                $ossClient = new \OSS\OssClient($accesskey, $secretkey, 'oss-accelerate.aliyuncs.com');
                $ossClient->uploadFile($bucket, $key, $filePath);
                
                $str = "https://" . $domain . "/" . $key;
                return result(0, 'success', $str);
            } elseif ($upload['upload_type'] == 'qnoss') {
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $accesskey = $upload['qnoss_access_key'];
                $secretkey = $upload['qnoss_secret_key'];
                $bucket = $upload['qnoss_bucket'];
                $domain = $upload['qnoss_domain'];
                
                $auth = new \Qiniu\Auth($accesskey, $secretkey);
                // 生成上传 Token
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new \Qiniu\Storage\UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list ($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return result(- 1, '上传失败');
                } else {
                    $str = $domain . "/" . $ret['key'];
                    return result(0, 'success', $str);
                }
            } elseif ($upload['upload_type'] == 'txcos') {
                
                // 上传后保存的文件名
                $key = time() . mt_rand(999, 9999) . ".$extension";
                
                $file = fopen($_FILES["file"]["tmp_name"], "rb");
                
                $accesskey = $upload['txcos_secret_id'];
                $secretkey = $upload['txcos_secret_key'];
                $bucket = $upload['txcos_bucket'];
                $domain = $upload['txcos_region'];
                
                $cosClient = new \Qcloud\Cos\Client([
                    'region' => $domain,
                    'schema' => "https",
                    'credentials' => [
                        'secretId' => $accesskey,
                        'secretKey' => $secretkey
                    ]
                ]);
                
                $result = $cosClient->putObject([
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file
                ]);
                
                $str = "https://" . $bucket . ".cos." . $domain . ".myqcloud.com/" . $key;
                return result(0, 'success', $str);
            }
        } catch (\Exception $e) {
            Log::write("upload 失败" . json_encode($e->getTrace()), 'info');
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    function updateCard($log_no, $price)
    {
        Db::startTrans();
        try {
            
            $log = FigureCardLog::where('log_no', $log_no)->find();
            
            if ($log['pay_status'] == 2) {
                exit();
            }
            
            $log['money'] = (float) $log['money'];
            $price = (float) $price;
            
            if (bccomp($log['money'], $price, 2) != 0) {
                Log::error("Index updateCard  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            
            FigureCardLog::where('log_no', $log_no)->update([
                'pay_status' => 2
            ]);
            
            $time = time();
            $arr = array();
            $card =[];
            for ($i = 0; $i < $log['quantity']; $i ++) {
                
                $card[] = $this->createCard($card);

                $arr[] = array(
                    'partner_id' => $log['partner_id'],
                    'goods_id' => $log['goods_id'],
                    'log_id' => $log['id'],
                    'name' => $log['goods_name'],
                    'member_id' => $log['member_id'],
                    'member_name' => $log['member_name'],
                    'day' => $log['goods_day'],
                    'point' => $log['goods_point'],
                    'avatar_twin_count' => $log['goods_avatar_twin_count'],
                    'voice_twin_count' => $log['goods_voice_twin_count'],
                    'second' => $log['goods_second'],
                    'second_infinite' => $log['goods_second_infinite'],
                    'card' => $card[$i],
                    'create_time' => $time
                );
            }
            
            if (! empty($arr)) {
                $card = new FigureCard();
                $card->insertAll($arr);
            }
            
            FigureCardGoods::where('id', $log['goods_id'])->save([
                'sold' => Db::raw('sold+' . $log['count']),
                'inventory' => Db::raw('inventory-' . $log['count'])
            ]);
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("Index updateCard 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
            print_r([
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
                'trace' => $e->getTrace()
            ]);
            exit();
        }
    }

    function createCard($card,$length = 12)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        
        $str = "";
        for ($i = 0; $i < $length; $i ++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        
        $info = Db::table("wjyk_figure_card")->where("card", $str)->find();
        if ($info) {
            $this->createCard($card);
        }
        if (in_array($str,$card)) {
            $this->createCard($card);
        }
        return $str;
    }

    public  function getHelpTutoria(){
        $request = $this->request;
        $param = $request->param();
        $pindex = max(1, intval(input('page')));
        $psize = empty($param['psize']) ? 10 : intval($param['psize']);
        $HelpTutoriaModel = new HelpTutoria();
        $total = $HelpTutoriaModel->where(['delete_time' => null])->count();
        $list =  $HelpTutoriaModel->order('sort', 'desc')->where(['delete_time' => null])
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    public  function getHelpTutoriaInfo(){
        $request = $this->request;
        $param = $request->param();
        $HelpTutoriaModel = new HelpTutoria();
        $list =  $HelpTutoriaModel->where(['delete_time' => null,'id' =>$param['id'] ])
            ->find();

        return result(0, 'success', $list);
    }

    /**
     * 客服配置
     * http://aigc.weijuyunke.cn/mobile/index/customerConfig
     */
    public function customerConfig()
    {

        try {
            $set = sysconfig('customer');

            if (empty($set)) {
                $set = [];
            }

            return result(0, 'success', $set);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }

    }


    /**
     * 流冠代理ip
     * http://aigc.weijuyunke.cn/mobile/index/getliuguan
     */
    public function getliuguan(){
        try {
            $request = $this->request;
            $param = $request->param();
            $getipHost = 'http://api.hailiangip.com:8422';

            $siteSet = sysconfig('site');
            $orderId = $siteSet['liuguang_ordersn'];            #用户编号
            $secret = $siteSet['liuguang_appsecret'];            #秘钥
            $time = time();        #当前时间戳
            $type = 1;            #ip协议  1表示HTTP/HTTPS
            $num = 1;                #提取数量 1-200之间
            $pid = $param['province_id'];            #省份 -1表示中国
            $cid = $param['city_id'];            #城市	可为空
            $unbindTime = 600;        #占用时长（单位秒）
            $dataType = 0;        #返回的数据格式 0表示json
            $noDuplicate = 0;        #是否去重 0表示不去重 1表示24小时去重
            $singleIp = 0;        #异常切换  0表示切换  1表示不切换

            $sign = strtolower(md5('orderId=' . $orderId . '&secret=' . $secret . '&time=' . $time));

            $getipUrl = '/api/getIp?type=' . $type . '&num=' . $num . '&pid=' . $pid . '&unbindTime=' . $unbindTime . '&cid=' . $cid . '&orderId=' . $orderId . '&time=' . $time . '&sign=' . $sign . '&noDuplicate=' . $noDuplicate . '&dataType=' . $dataType . '&lineSeparator=0&singleIp=' . $singleIp;


            $getipLink = $getipHost . $getipUrl;
//	 echo $getipLink;exit;

            // 用get方式获取
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $getipLink);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $ret = curl_exec($ch);
            curl_close($ch);
            // var_dump($ret);exit;

            $retArr = json_decode($ret, true);
            if ($retArr['code'] == 0) {
                return result(0, 'success', $retArr['data'][0]['ip'].':'.$retArr['data'][0]['port']);

            }
        }catch (Exception $exception){
            return result(- 1, '异常' . $exception->getMessage());
        }

    }

    public function liuGuanProvince(){
        $json_string = file_get_contents(root_path() . "public/json/liuguanProvince.json");
        $list = json_decode($json_string, true);
        return result(0, 'success',$list );

    }


    public function way(){
        $request = $this->request;
        $param = $request->param();
        $model = new \app\admin\model\FigureWayName();

        if ( isset($param['type'] ) && $param['type'] ==1){
            $list = $model
                ->where(['status' =>1])
                ->where('id','<>',1)
                ->where('id','<>',4)
                ->order('sort','asc')
                ->select();
        }else{
            $list = $model
                ->where(['status' =>1])
                ->order('sort','asc')
                ->select();
        }
        return result(0, 'success',$list );
    }


    public function proxy(){
      /*  try {*/
            $request = $this->request;
            $param = $request->param();
            $getipHost = 'https://sch.shanchendaili.com/api.html';

            $siteSet = sysconfig('site');
                     #秘钥
              #异常切换  0表示切换  1表示不切换


            $getipUrl = '?action=get_ip&key='.'HU54aa50d18174600127iv7F'.'&time=3&count=1&type=json&only=0&province=2002&city=2099';

            $getipLink = $getipHost . $getipUrl;
           // var_dump($getipLink);exit;
//	 echo $getipLink;exit;

            // 用get方式获取
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $getipLink);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $ret = curl_exec($ch);
            curl_close($ch);
            // var_dump($ret);exit;
            $retArr = json_decode($ret, true);
            return result(0, 'success', $retArr['list'][0]['sever'].':'.$retArr['list'][0]['port']);

      /*  }catch (Exception $exception){
            return result(- 1, '异常' . $exception->getMessage());
        }*/

    }
}